﻿using System;
using System.Collections.Generic;
using System.Linq;
using SQLStore;
using System.Data.Entity.Migrations;
using System.Linq.Expressions;
using Models;

namespace Services
{
    public class CategoryServices : IDataAccess<Category>
    {
        CMSDBContext db ;

        public CategoryServices()
        {
            db = new CMSDBContext();
        }

        public CategoryServices(string connectionString)
        {
            db = new CMSDBContext(connectionString);
        }
        public int Delete(object objValue)
        {
            Guid categoryId = Guid.Parse(objValue.ToString());
            var entity = db.Set<Category>().Where(t => t.CategoryId == categoryId).FirstOrDefault();
            db.Set<Category>().Remove(entity);

            return Save();
        }

        public bool Exists(Expression<Func<Category, bool>> exp)
        {
            return db.Set<Category>().Any(exp);
        }

        public bool Exists(object objValue)
        {
            string categoryName = objValue.ToString();
            return db.Set<Category>().Any(t => t.CategoryName == categoryName);
        }


        public Category GetByID(object objValue)
        {
            Guid categoryId = Guid.Parse(objValue.ToString());
            return db.Set<Category>().Where(t => t.CategoryId == categoryId).FirstOrDefault();
        }
        public Category GetByName(string name)
        {
            return db.Set<Category>().Where(t => t.CategoryName == name).FirstOrDefault();
        }

        public Category GetByUrl(string categoryUrl)
        {
            return db.Set<Category>().Where(t => t.CategoryUrl == categoryUrl).FirstOrDefault();
        }
        public List<Category> GetList(Expression<Func<Category, bool>> exp)
        {
            return db.Set<Category>().Where(exp).OrderBy(t => t.Sort).ToList();
        }

        public int Save(Category entity)
        {
            db.Set<Category>().AddOrUpdate(entity);
            return Save();
        }
        int Save()
        {
            return db.SaveChanges();
        }
    }
}